# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: leon, chensili

import datetime
import re
import subprocess

from sqlalchemy import create_engine
import coin.base.database.util as db_util
from coin.exchange.base.kr_rest.constants import usd_variant_list
from coin.strategy.mm.subscription import SubscriptionRequest
from coin.base.query_util import query_exchange_rates
from xunkemgmt_client.client.util.query_util import (get_exchange_api_id_from_request as
                                                     get_exchange_api_id_from_request_impl)

def to_book_builder_symbol(product, sub_request):
  symbol = product.native_symbol
  if (product.product_type == 'Futures' and product.exchange == 'Okex' and product.is_perpetual):
    symbol = product.native_symbol_v3
  elif (product.exchange == 'Okex'
        and (sub_request is not None and sub_request.api_version in ['v3', 'v3_realtime'])):
    symbol = product.native_symbol_v3
  return symbol


def to_book_builder_exchange_symbol(product, sub_request=None):
  exchange = product.exchange
  symbol = to_book_builder_symbol(product, sub_request)
  return exchange, symbol


def to_datetime_or_none(timestamp):
  if timestamp == 0:
    return None
  else:
    return datetime.datetime.utcfromtimestamp(timestamp / (10.**9))


def to_time_str_or_none(timestamp):
  if timestamp:
    return datetime.datetime.utcfromtimestamp(timestamp / (10.**9)).strftime('%Y-%m-%d %H:%M:%S.%f')
  else:
    return None


def avg_or_none(total, count):
  if count == 0:
    return None
  else:
    return total / count


def ratio_or_none(count1, count2):
  if count2 == 0:
    return None
  else:
    return count1 / count2


def fetch_git_commit_sha_datetime(git_commit):
  if git_commit == 'HEAD':
    git_commit_sha = subprocess.check_output(['git', 'rev-parse', 'HEAD']).strip().decode()
  else:
    pattern = re.compile(r'\b[0-9a-f]{40}\b')
    match = pattern.match(git_commit)
    if not match:
      raise ValueError(git_commit)
    else:
      git_commit_sha = git_commit

  git_commit_datetime_cmd = "TZ=UTC git show --quiet --date=local --format='%cd'"
  git_commit_datetime_str = subprocess.check_output(git_commit_datetime_cmd,
                                                    shell=True).strip().decode()
  git_commit_datetime = datetime.datetime.strptime(git_commit_datetime_str, '%a %b %d %H:%M:%S %Y')
  return git_commit_datetime, git_commit_sha


def gen_engine():
  engine = create_engine(
      'mysql+mysqldb://feed_stat_querier:#dXfc%DGtXg%SfBX@coin-db.corp.prestolabs.io/feed_stat_20200803',  # noqa: E501
      echo=False)
  return engine


def gen_engine_for_importer():
  engine = create_engine(
      'mysql+mysqldb://feed_stat_importer:vRfgb2!#dD#ge!Qg@coin-db.corp.prestolabs.io/feed_stat_20200803',  # noqa: E501
      echo=False)
  return engine


def get_exchange_api_id_from_request(request_list):
  return get_exchange_api_id_from_request_impl(request_list)


def query_quote_to_usd_exchange_rate(quotes: list):
  ex_rates = query_exchange_rates(quotes, 'USD')
  return dict(zip(quotes, ex_rates))


def datetime_span(start, end, delta):
  assert isinstance(start, datetime.datetime)
  assert isinstance(end, datetime.datetime)
  assert isinstance(delta, datetime.timedelta)
  cur_datetime = start
  while cur_datetime <= end:
    yield cur_datetime
    cur_datetime += delta


def gen_engine_for_instrument_feed_querier():
  engine = create_engine(
      'mysql+mysqldb://querier:WBQvz1cQAA$Ewd4g@coin-db.corp.prestolabs.io/coin_instrument_feed',
      echo=False)
  return engine
